package Underworld_Survival;

import java.io.IOException;
import java.util.*;

import static Underworld_Survival.GameOutput.MsgType;

public class Game {

    public static GameOutput gameOutput=new GameOutput();
    public static Player player=new Player("",100,30,
            15,5,5);
    static int stage=0;//游戏的关卡数
    static int stageOfMerchantAppears[]={0};
    static EventManager eventManager=new EventManager();//事件管理器，用于发生随机事件

    public static int inputCheck(int min,int max){
        int length=max-min+1;
        String[] result=new String[length];
        for(int i=0;i<length;i++){
            result[i]=String.valueOf(min+i);
        }
        Scanner sc=new Scanner(System.in);
        while(true){
            String input=sc.nextLine();
            for(int i=0;i<length;i++){
                if(result[i].equals(input)){
                    try{
                        int select=Integer.valueOf(result[i]);
                        return select;
                    }catch (NumberFormatException e){
                        gameOutput.println(MsgType.WARNING,"无法将字符串转化为整数");
                    }
                }
            }
            gameOutput.println(MsgType.SYSTEM,"输入有误，请重新输入！");
        }
    }//只能输入min,max之间的整数，输入其他提示请重新输入

    public static void pressAnyKeyToContinue(){
        Scanner sc=new Scanner(System.in);
        gameOutput.println(MsgType.SYSTEM,"按任意键和enter，继续游戏");
        sc.nextLine();
    }

    public static String padChineseText(String chineseText, int targetWidth) {
        int chineseCharCount = chineseText.length();
        int extraSpace = targetWidth - chineseCharCount * 2;
        StringBuilder sb = new StringBuilder(chineseText);
        for (int i = 0; i < extraSpace; i++) {
            sb.append(" ");
        }
        return sb.toString();
    }

    public static void afterEvent(){
        EventManager eventManager=new EventManager();
        boolean merchant=Math.random()<(stage-stageOfMerchantAppears[0])/50.0;//出现商人概率
        if(merchant||stage-stageOfMerchantAppears[0]>=8){
            pressAnyKeyToContinue();
            eventManager.triggerFixedEvent(new mysteriousMerchant_Event(),player);
            stageOfMerchantAppears[0]=stage;
        }
        gameOutput.println(MsgType.SYSTEM,"上一次出现商人关卡："+stageOfMerchantAppears[0]+"   当前关卡："+stage);
        GameOutput.ShowPlayer.basicProperty();
        GameOutput.sharedInformation.showBuff(player);
        Scanner sc=new Scanner(System.in);
        int select;
        while(true){
            gameOutput.println(MsgType.SYSTEM,"接下来，你想：");
            GameOutput.GameUI.gameLoopInterface();
            //1.进入下一房间  2.打开背包  3.查看状态  4.查看装备  5.常驻商店  6.退出游戏
            select=inputCheck(1,6);
            if(select==1){break;}//进入下一个房间
            else if(select==2){//打开背包
                GameOutput.ShowPlayer.checkBag();//展示背包所有物品
                while(true) {
                    GameOutput.GameUI.backpackInterface();
                    int select1 = inputCheck(1, 9);
                    //1.返回     2.使用食物  3.使用卷轴  4.使用道具  5.售卖物品
                    //6.装备武器  7.装备防具  8.装备鞋子  9.查看物品详情
                    if(select1==1){break;}//返回上一级
                    else if(select1==2||select1==3||select1==4){
                        //使用食物，使用卷轴，使用道具
                        List<Item> distinctNameList;
                        if(select1==2){
                            gameOutput.println(MsgType.SYSTEM,"请选择你要使用的食物：");
                            distinctNameList = new ArrayList<>((List) player.bag.showFoodVertically());
                        }else if(select1==3){
                            gameOutput.println(MsgType.SYSTEM,"请选择你要使用的卷轴：");
                            distinctNameList = new ArrayList<>((List) player.bag.showScrollVertically());
                        }else{
                            gameOutput.println(MsgType.SYSTEM,"请选择你要使用的道具：");
                            distinctNameList = new ArrayList<>((List) player.bag.showOtherItemVertically());
                        }
                        if (!distinctNameList.isEmpty()) {
                            gameOutput.println(MsgType.BAG,(distinctNameList.size()+1)+".返回");
                            int select2 = inputCheck(1, distinctNameList.size()+1);
                            if(select2!=distinctNameList.size()+1){
                                player.useSupply(distinctNameList.get(select2-1));
                            }
                        }
                    }
                    else if(select1==6||select1==7||select1==8){
                        //装备武器，防具，鞋子
                        List<Equipment> distinctNameList;
                        if(select1==6){
                            gameOutput.println(MsgType.SYSTEM,"请选择你要装备的武器：");
                            distinctNameList = new ArrayList<>((List)player.bag.showWeaponVertically());
                        } else if (select1 == 7) {
                            gameOutput.println(MsgType.SYSTEM,"请选择你要装备的防具：");
                            distinctNameList = new ArrayList<>((List)player.bag.showArmorVertically());
                        }else{
                            gameOutput.println(MsgType.SYSTEM,"请选择你要装备的鞋子：");
                            distinctNameList = new ArrayList<>((List)player.bag.showShoeVertically());
                        }
                        if (!distinctNameList.isEmpty()) {
                            gameOutput.println(MsgType.BAG,(distinctNameList.size()+1)+".返回");
                            int select2 = inputCheck(1, distinctNameList.size()+1);
                            if(select2!=distinctNameList.size()+1){
                                player.equipWithEquipment(distinctNameList.get(select2-1));
                            }
                        }

                    }
                    else if (select1 == 5) {//售卖物品
                        gameOutput.println(MsgType.SYSTEM,"请选择你要出售的物品：");
                        List<? extends Item> distinctNameList = player.bag.showBagVertically();
                        if (!distinctNameList.isEmpty()) {
                            gameOutput.println(MsgType.BAG,(distinctNameList.size()+1)+".停止出售");
                            int select2 = inputCheck(1, distinctNameList.size()+1);
                            if(select2!=distinctNameList.size()+1){
                                player.sellItem(distinctNameList.get(select2-1));
                            }
                        }
                    }
                    else if(select1==9){player.bag.showBagDetailed();}
                }
            }
            else if(select==3){
                GameOutput.ShowPlayer.status();//展示状态（血量,buff,技能，增益等）
                while(true){
                    GameOutput.GameUI.statusInterface();
                    int select1=inputCheck(1,4);
                    //1.返回  2.属性详情  3.增益详情  4.使用卷轴
                    gameOutput.println(MsgType.SYSTEM,"请选择你要进行的操作：");
                    if(select1==1){break;}//返回上一级
                    else if(select1==2){
                        GameOutput.ShowPlayer.detailedProperty1();
                    }
                    else if(select1==3){
                        System.out.println(player.getEffectManager().printEffects(player));
                    }
                    else if(select1==4){
                        List<Item> distinctNameList;
                        distinctNameList = new ArrayList<>((List) player.bag.showScrollVertically());
                        if (!distinctNameList.isEmpty()) {
                            gameOutput.println(MsgType.BAG,(distinctNameList.size()+1)+".返回");
                            int select2 = inputCheck(1, distinctNameList.size()+1);
                            if(select2!=distinctNameList.size()+1){
                                player.useSupply(distinctNameList.get(select2-1));
                            }
                        }
                    }
                }
            }
            else if(select==4){//4.查看装备
                player.bag.showWeaponHorizontally();
                player.bag.showArmorHorizontally();
                player.bag.showShoeHorizontally();
                GameOutput.ShowPlayer.equipment();
                while(true){
                    GameOutput.GameUI.equipmentInterface();
                    //1.返回上级  2.装备武器  3.装备防具  4.装备鞋子  5.装备详情
                    //6.卸下武器  7.卸下防具  8.卸下鞋子
                    int select1=inputCheck(1,8);
                    if(select1==1){break;}//返回上一级
                    else if(select1==2||select1==3||select1==4){
                        //装备武器，防具，鞋子
                        List<Equipment> distinctNameList;
                        if(select1==2){
                            gameOutput.println(MsgType.SYSTEM,"请选择你要装备的武器：");
                            distinctNameList = new ArrayList<>((List)player.bag.showWeaponVertically());
                        } else if (select1 == 3) {
                            gameOutput.println(MsgType.SYSTEM,"请选择你要装备的防具：");
                            distinctNameList = new ArrayList<>((List)player.bag.showArmorVertically());
                        }else{
                            gameOutput.println(MsgType.SYSTEM,"请选择你要装备的鞋子：");
                            distinctNameList = new ArrayList<>((List)player.bag.showShoeVertically());
                        }
                        if (!distinctNameList.isEmpty()) {
                            gameOutput.println(MsgType.BAG,(distinctNameList.size()+1)+".返回");
                            int select2 = inputCheck(1, distinctNameList.size()+1);
                            if(select2!=distinctNameList.size()+1){
                                player.equipWithEquipment(distinctNameList.get(select2-1));
                            }
                        }
                    }
                    else if(select1==5){
                        GameOutput.ShowPlayer.equipmentDetailed();
                    }
                    else if(select1==6){
                        if(player.getWeaponSlot().hasWeapon()){
                            player.removeEquipment(player.getWeaponSlot().getEquippedItem());
                        }
                    }
                    else if(select1==7){
                        if(player.getArmorSlot().hasArmor()){
                            player.removeEquipment(player.getArmorSlot().getEquippedItem());
                        }
                    }
                    else if(select1==8) {
                        if(player.getShoeSlot().hasShoe()){
                            player.removeEquipment(player.getShoeSlot().getEquippedItem());
                        }
                    }
                }
            }
            else if(select==5){//常驻商店
                List<Item> goods = MerchantConfig.permanentGoods();//商人商品类表
                GameOutput.GameUI.storeInterface();
                gameOutput.println(MsgType.SHOP,(goods.size()+1)+".返回");
                gameOutput.println(MsgType.SYSTEM,"请选择你要购买的商品：");
                GameOutput.ShowPlayer.estate();//展示财产
                int select1;
                while(true){
                    select1=inputCheck(1,goods.size()+1);
                    if(select1==goods.size()+1) break;
                    if(goods.get(select1-1).getPurchaseCurrency().equals(CurrencyType.GOLD)){
                        if(player.useGold(goods.get(select1-1).getPriceOfPurchase())){
                            player.obtainItem(goods.get(select1-1));
                        }
                    }else{
                        if(player.useDiamond(goods.get(select1-1).getPriceOfPurchase())){
                            player.obtainItem(goods.get(select1-1));
                        }
                    }
                }
            }
            else if(select==6){//退出游戏
                try {
                    GameDataSaveManager.saveGame(player);
                    System.out.println("游戏数据保存成功！");
                } catch (IOException e) {
                    System.err.println("保存游戏数据时出现错误：" + e.getMessage());
                    e.printStackTrace();
                }
                player=new Player("",100,30,
                        15,5,5);
                gameBegin();
            }
        }
    }

    public static void gameBegin(){
        GameOutput.GameUI.mainGameInterface();
        //1.新游戏，2.继续游戏，3.游戏介绍，4.退出
        GameRegistry.initialize();
        while(true){
            int select=inputCheck(1,4);
            if(select==1){break;}
            else if(select==2){
                try {
                    player=GameDataSaveManager.loadGame();
                    System.out.println("游戏数据加载成功！");
                } catch (IOException e) {
                    System.err.println("加载游戏数据时出现错误：" + e.getMessage());
                    e.printStackTrace();
                } catch (ClassNotFoundException e) {
                    throw new RuntimeException(e);
                }
                GameOutput.ShowPlayer.info();
                afterEvent();
                gameLoop();
            }
            else if(select==3){
                GameOutput.GameUI.gameIntroduction();
            }
            else if(select==4){System.exit(0);}
            else{}
        }
        gameOutput.println(MsgType.STORY,"欢迎来到地牢探险！\n此地牢无名无姓，却吞噬过无数像你一样的探索者。它的墙壁会呼吸，走廊会生长。");
        pressAnyKeyToContinue();
        gameOutput.println(MsgType.STORY,"每一次踏入都会发现全新的炼狱——有人说这是诅咒，也有人坚信这是神明的试炼场。");
        pressAnyKeyToContinue();
        gameOutput.println(MsgType.STORY,"这地牢之底沉睡着连最年长的吟游诗人都不敢歌颂的存在，但通往它的道路布满诡谲的馈赠");
        pressAnyKeyToContinue();
        gameOutput.println(MsgType.SYSTEM,"游戏开始前，先给自己起个名字吧~");
        Scanner sc=new Scanner(System.in);
        String name=sc.nextLine();
        player.setName(name);
        gameOutput.println(MsgType.SYSTEM,"很好，那么你希望你的形象是：");
        System.out.println("很好，那么你希望你的形象\uD83D\uDC64是：");
        System.out.println("1.\uD83D\uDC64  2.\uD83E\uDDCD  3.\uD83D\uDE0E  4.\uD83E\uDDDB  5.\uD83E\uDDDA");//👤🧍😎🧛🧚
        System.out.println("6.\uD83E\uDDDC  7.\uD83E\uDDB8  8.\uD83D\uDC7B  9.\uD83E\uDD16  10.\uD83E\uDDDF");//🧜🦸👻🤖🧟
        int select=inputCheck(1,10);
        if(select==1){ player.setName(player.getName()+"\uD83D\uDC64");
        }else if(select==2){player.setName(player.getName()+"\uD83E\uDDCD");
        }else if(select==3){player.setName(player.getName()+"\uD83D\uDE0E");
        }else if(select==4){player.setName(player.getName()+"\uD83E\uDDDB");
        } else if(select==5){player.setName(player.getName()+"\uD83E\uDDDA");
        } else if(select==6){player.setName(player.getName()+"\uD83E\uDDDC");
        } else if(select==7){player.setName(player.getName()+"\uD83E\uDDB8");
        } else if(select==8){player.setName(player.getName()+"\uD83D\uDC7B");
        }else if(select==9){player.setName(player.getName()+"\uD83E\uDD16");
        } else{player.setName(player.getName()+"\uD83E\uDDDF");
        }
        gameOutput.println(MsgType.SYSTEM,"游戏即将开始！"+player.getName()+",迎接你的旅程吧~");
        pressAnyKeyToContinue();
        gameOutput.println(MsgType.SYSTEM,player.getName()+"的所有信息为：");
        GameOutput.ShowPlayer.info();
        gameOutput.println(MsgType.SYSTEM,"你准备好了吗？");
        pressAnyKeyToContinue();
        player.bag.getOtherItem().add(new resurrectionMedicine());//回生药
        player.learnSkill(new normalAttack());
        afterEvent();
    }
    public static void gameLoop(){
        while(true){
            gameOutput.println(MsgType.SYSTEM,"-----------------------------------------------------------------");
            stage++;
            gameOutput.print(MsgType.SYSTEM,"第"+stage+"个房间:  ");
            if(stage==6){
                gameOutput.println(MsgType.EVENT,"进入这次房间，你感觉你的脚有一股神奇的力量。\n"+
                        "你学会了无影脚！可以给对手造成速度的2.7倍伤害");
                player.learnSkill(new shadowlessKick());
            }else if(stage==15){
                gameOutput.println(MsgType.EVENT,"进入这次房间，你感觉你的身体有一股神奇的力量。\n"+
                        "你学会了泰山压顶！可以给对手造成防御的2.8倍伤害");
                player.learnSkill(new overwhelmingSmash());
            }else if(stage==30){
                gameOutput.println(MsgType.EVENT,"进入这次房间，你感觉你的手有一股神奇的力量。\n"+
                        "学会了降龙十八掌！可以给对手造成力量的2.1倍伤害");
                player.learnSkill(new eighteenDragon_SubduingPalms());
            }
            eventManager.triggerEvent(player);
            gameOutput.println(MsgType.GET,"通关奖励：50"+CurrencyType.GOLD.getDescription()+
                    "   10"+CurrencyType.DIAMOND.getDescription());
            player.rewardGold(50);
            player.rewardDiamond(10);
            afterEvent();
        }

    }

    public static void main(String[] args) {
        gameBegin();
        gameLoop();
    }

//全局小游戏
//1.猜硬币正反
public static boolean guessTheCoin(){
    gameOutput.println(MsgType.GAME,"房顶空降一枚硬币，在桌上翻转一会后被筹码挡住了\n1.正面     2.反面");
    gameOutput.println(MsgType.GAME,"你的猜测是：");
    int select=inputCheck(1,2);
    if((select==1&&Math.random()<0.5)||(select==2&&(Math.random()>=0.5))){
        gameOutput.println(MsgType.GET,"恭喜你，猜对了！获得奖励");
        return true;
    }else{
        gameOutput.println(MsgType.EVENT,"很遗憾，你猜错了，赌注被没收");
        return false;
    }
}
//2.两次机会猜一个数字
public static boolean guessTheNumber(){
    Random random=new Random();
    int chance=2;
    int answer=random.nextInt(1,11);//1-10之间随机数字
    gameOutput.println(MsgType.GAME,"桌上出现了一个大大的问号？？？\n你猜测这个数字是：");
    while (chance > 0) {
        int number=inputCheck(1,10);
        chance--;
        if(number==answer){
            gameOutput.println(MsgType.GAME,"恭喜你！猜对啦。获得奖励");
            return true;
        }else if(chance==0){
            gameOutput.println(MsgType.GAME,"很遗憾，你没猜对.....");
            return false;
        }
        else if(number<answer){
            gameOutput.println(MsgType.GAME,"猜小啦,你还有1次机会");
        }else{
            gameOutput.println(MsgType.GAME,"猜大啦,你还有1次机会");
        }
    }
    return true;
}
//3.记忆翻牌游戏
public static boolean memoryGame(){
    String[] cards = {"<烈焰之剑>", "<烈焰之剑>", "[精华草]", "[精华草]",
            "【血量卷轴】", "【血量卷轴】", "{回生药}", "{回生药}"};
    boolean[] flipped = new boolean[8];
    int matches = 0;
    for (int i = 0; i < cards.length; i++) {
        int j = (int) (Math.random() * cards.length);
        String temp = cards[i];
        cards[i] = cards[j];
        cards[j] = temp;
    }
    while (matches < 4) {
        String[] display = new String[8];
        for (int i = 0; i < 8; i++) {
            display[i] = flipped[i] ? cards[i] : "?";
        }
        String cardFace=Arrays.toString(display);
        System.out.println("当前牌面: " + cardFace);
        System.out.println("请输入两位数，代表你要翻开的牌面：");
        int select=inputCheck(12,87);
        int first =select/10;
        System.out.println(cards[first-1]);
        int second =select%10;
        System.out.println(cards[second-1]);
        if (cards[first-1].equals(cards[second-1]) && !flipped[first-1]) {
            flipped[first-1] = flipped[second-1] = true;
            matches++;
            System.out.println("匹配成功！");
        } else {
            System.out.println("不匹配！");
        }
    }
    return true;
}

}
